package org.dizena.modules.wss.wsconfig;

import lombok.extern.slf4j.Slf4j;
import org.dizena.base.shiro.SessionUserUtil;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@Component
public class WsInterceptor implements HandshakeInterceptor
{
    /**
     * 握手之前
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes)
    {
        log.info("web socket 握手之前......");
        if (request instanceof ServletServerHttpRequest)
        {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest req = servletRequest.getServletRequest();
            String cid = req.getParameter("cid");
            attributes.put("cid", cid);
            log.info("attributes put cid {} ", cid);

            if (SessionUserUtil.getSessionUser().getId().equals(cid))
            {
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 握手之后
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception)
    {
        log.info("web socket 握手之后......");
    }

}